package controllers.admin;

import java.util.ArrayList;
import java.util.List;

import models.Message;
import models.Order;
import models.Message.MessageType;
import models.Order.OrderStatus;
import models.Administrator;
import models.OrderItem;
import models.QueryBean;
import models.RemittanceConfirm;
import models.RemittanceConfirm.ConfirmStatus;
import play.mvc.Controller;
import play.mvc.With;
import service.MessageService;
import controllers.GlobalVariables;
import controllers.Secure;
import controllers.ValidationUtil;

@With(Secure.class)
public class Orders extends Controller {
	//============================历史订单开始=====================
	
	/**
	 * 跳转到发货确认页面。
	 */
	public static void indexOrder() {
		render();
	}
	/**
	 * 获取待发货确认的订单。
	 */
	public static void orderTable(QueryBean queryBean, OrderStatus orderStatus) {
		if(queryBean == null) queryBean = new QueryBean();
		
		StringBuilder hql = new StringBuilder();
		List<Object> objs = new ArrayList<Object>();
		
		if(!ValidationUtil.isEmpty(queryBean.keyword)) {
			hql.append("(deliveryAddress like '%"+queryBean.keyword+"%' ");
			hql.append("or receiver like '%"+queryBean.keyword+"%' ");
			if(ValidationUtil.isLong(queryBean.keyword)) {
				hql.append("or id = ? ");
				objs.add(Long.valueOf(queryBean.keyword));
			}
			hql.append(") ");
			if(orderStatus != null) {
				hql.append("and ");
			}
		}
		
		if(orderStatus != null) {
			hql.append("orderStatus=? ");
			objs.add(orderStatus);
		}
		
		if(!ValidationUtil.isEmpty(queryBean.orderby)) {
			if(queryBean.isDesc) {
				hql.append(" order by " + queryBean.orderby +" desc ");
			} else {
				hql.append(" order by " + queryBean.orderby);
			}
			
		} else {
			hql.append(" order by lastModifiedAt desc");
		}
		
		queryBean.totalQuantity = Order.count(hql.toString(), objs.toArray());
		queryBean.pageCaculate();
		
		List<Order> orders = Order
			.find(hql.toString(), objs.toArray()).fetch((int)queryBean.currentPage, queryBean.quantityEachPage);
		render(orders, queryBean);
	}
	
	/**
	 * 删除指定定单。
	 */
	public static void deleteOrder(long id) {
		Order order = Order.findById(id);
		if(order == null) return;
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		
		MessageService.adminSendMessage("你的订单("+order.id+")已经被管理员删除。", 
				MessageType.OTHER, order.createByUser, admin);
		RemittanceConfirm.delete("order.id=?", id);
		order.delete();
	}
	
	/**
	 * 查看订单详细页面。
	 * @param id
	 */
	public static void showOrder(long id) {
		Order order = Order.findById(id);
		if(order==null) {
			validation.addError("errMsg", "此订单("+id+")可能已被删除。");
			params.flash();
			validation.keep();
			indexDeliveryConfirm();
		}
		
		List<RemittanceConfirm> remittanceConfirms = RemittanceConfirm.find("order.id", id).fetch();
		render(order, remittanceConfirms);
	}
	
	//============================历史订单结束=====================
	
	//============================汇款确认开始=====================
	/**
	 * 跳转到订单确认页面。
	 */
	public static void indexRemittanceConfirm(){
		render();
	}
	
	/**
	 * 获取remittanceConfirmTable代码。
	 */
	public static void remittanceConfirmTable(QueryBean queryBean, ConfirmStatus confirmStatus) {
		if(queryBean == null) queryBean = new QueryBean();
		
		StringBuilder hql = new StringBuilder();
		List<Object> objs = new ArrayList<Object>();
		
		if(!ValidationUtil.isEmpty(queryBean.keyword)) {
			hql.append("(bankName like '%"+queryBean.keyword+"%' ");
			hql.append("or paierName like '%"+queryBean.keyword+"%' ");
			if(ValidationUtil.isLong(queryBean.keyword)) {
				hql.append("or id = ? or order.id = ? ");
				objs.add(Long.valueOf(queryBean.keyword));
				objs.add(Long.valueOf(queryBean.keyword));
			}
			hql.append(" ) ");
		}
		
		if(!ValidationUtil.isEmpty(confirmStatus)) {
			if(hql.length() != 0) hql.append(" and ");
			hql.append(" confirmStatus=?");
			objs.add(confirmStatus);
		}
		
		if(!ValidationUtil.isEmpty(queryBean.orderby)) {
			if(queryBean.isDesc) {
				hql.append(" order by " + queryBean.orderby +" desc ");
			} else {
				hql.append(" order by " + queryBean.orderby);
			}
			
		} else {
			hql.append(" order by lastModifiedAt desc");
		}
		
		queryBean.totalQuantity = RemittanceConfirm.count(hql.toString(), objs.toArray());
		queryBean.pageCaculate();
		
		List<RemittanceConfirm> remittanceConfirms = RemittanceConfirm
			.find(hql.toString(), objs.toArray()).fetch((int)queryBean.currentPage, queryBean.quantityEachPage);
		render(remittanceConfirms, queryBean);
	}
	
	/**
	 * 订单详细信息。
	 */
	public static void showRemittanceConfirm(long id) {
		RemittanceConfirm remittanceConfirm = RemittanceConfirm.findById(id);
		List<OrderItem> items = OrderItem.find("order.id=?", remittanceConfirm.order.id).fetch();
		remittanceConfirm.order.orderItems = items;
		render(remittanceConfirm);
	}
	
	/**
	 * 确认付款。
	 * @param id
	 * @param common
	 */
	public static void updateRemittanceConfirmResult(long id, boolean isPass, String common) {
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		
		RemittanceConfirm remittanceConfirm = RemittanceConfirm.findById(id);
		if(remittanceConfirm == null) {
			throw new RuntimeException("找不到ID为"+id+"的确认记录。");
		} 
		if(remittanceConfirm.confirmStatus != ConfirmStatus.NEW) {
			throw new RuntimeException("确认单（"+id+"）的确认状态已经被更变，请刷新页面。");
		}
		if(!isPass && ValidationUtil.isEmpty(common)) {
			throw new RuntimeException("确认不通过的话，请说明原因。");
		}
		
		if(isPass) {
			common = "您的汇款确认已通过，请查看你的订单("+remittanceConfirm.id+")详细状态。" + common;
			remittanceConfirm.order.orderStatus = OrderStatus.PAY_CONFIRM;
			remittanceConfirm.order.resetModifier(admin);
			remittanceConfirm.order.save();
			remittanceConfirm.resetModifier(admin);
			remittanceConfirm.confirmStatus = ConfirmStatus.PASS;
			remittanceConfirm.admin = admin;
			remittanceConfirm.save();
		} else {
			common = "您的汇款确认不通过，请查看你的订单("+remittanceConfirm.id+")详细状态。不通过原因：" + common;
			remittanceConfirm.order.orderStatus = OrderStatus.NEW;
			remittanceConfirm.order.resetModifier(admin);
			remittanceConfirm.order.save();
			remittanceConfirm.resetModifier(admin);
			remittanceConfirm.confirmStatus = ConfirmStatus.FAIL;
			remittanceConfirm.admin = admin;
			remittanceConfirm.save();
		}
		MessageService.adminSendMessage(common, MessageType.OTHER, remittanceConfirm.order.user, admin);
	}
	
	/**
	 * 删除指定确认单记录。
	 * @param id
	 */
	public static void deleteRemittanceConfirm(long id) {
		RemittanceConfirm remittanceConfirm = RemittanceConfirm.findById(id);
		if(remittanceConfirm == null) {
			throw new RuntimeException("找不到ID为"+id+"的确认记录。");
		} 
		if(remittanceConfirm.order.orderStatus == OrderStatus.SENDED 
				|| remittanceConfirm.order.orderStatus == OrderStatus.HISTORY) {
			throw new RuntimeException("订单已经发货，不能删除。");
		}
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		remittanceConfirm.order.orderStatus = OrderStatus.NEW;
		remittanceConfirm.order.resetModifier(admin);
		remittanceConfirm.order.save();
		MessageService.adminSendMessage("你的汇款确认单("+remittanceConfirm.order.id+")已经被管理员删除。", 
				MessageType.OTHER, remittanceConfirm.createByUser, admin);
		remittanceConfirm.delete();
	}
	
	//============================汇款确认结束=====================
	
	//============================发货确认开始=====================
	/**
	 * 跳转到发货确认页面。
	 */
	public static void indexDeliveryConfirm(){
		render();
	}
	/**
	 * 获取待发货确认的订单。
	 */
	public static void deliveryConfirmTable(QueryBean queryBean) {
		if(queryBean == null) queryBean = new QueryBean();
		
		StringBuilder hql = new StringBuilder();
		List<Object> objs = new ArrayList<Object>();
		
		hql.append(" orderStatus = ? ");
		objs.add(OrderStatus.PAY_CONFIRM);
		
		if(!ValidationUtil.isEmpty(queryBean.keyword)) {
			hql.append(" and (deliveryAddress like '%"+queryBean.keyword+"%' ");
			hql.append("or receiver like '%"+queryBean.keyword+"%' ");
			if(ValidationUtil.isLong(queryBean.keyword)) {
				hql.append("or id = ? ");
				objs.add(Long.valueOf(queryBean.keyword));
			}
			hql.append(") ");
		}
		
		if(!ValidationUtil.isEmpty(queryBean.orderby)) {
			if(queryBean.isDesc) {
				hql.append(" order by " + queryBean.orderby +" desc ");
			} else {
				hql.append(" order by " + queryBean.orderby);
			}
			
		} else {
			hql.append(" order by lastModifiedAt desc");
		}
		
		queryBean.totalQuantity = Order.count(hql.toString(), objs.toArray());
		queryBean.pageCaculate();
		
		List<Order> orders = Order
			.find(hql.toString(), objs.toArray()).fetch((int)queryBean.currentPage, queryBean.quantityEachPage);
		render(orders, queryBean);
	}
	
	/**
	 * 查看订单详细页面。
	 * @param id
	 */
	public static void showSendingOrder(long id) {
		Order order = Order.findById(id);
		if(order==null) {
			validation.addError("errMsg", "此订单("+id+")可能已被删除。");
			params.flash();
			validation.keep();
			indexDeliveryConfirm();
		}
		
		List<RemittanceConfirm> remittanceConfirms = RemittanceConfirm.find("order.id", id).fetch();
		render(order, remittanceConfirms);
	}
	
	/**
	 * 更新订单为已发货状态。
	 * @param id
	 */
	public static void updateOrderSended(long id) {
		Order order = Order.findById(id);
		if(order==null) {
			throw new RuntimeException("此订单("+id+")可能已被删除。");
		} else if(order.orderStatus != OrderStatus.PAY_CONFIRM) {
			throw new RuntimeException("此订单("+id+")可能已被被改变状态。");
		}
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		order.orderStatus = OrderStatus.SENDED;
		order.resetModifier(admin);
		order.save();
	}
	//============================发货确认结束=====================
}